<template>
  <div class="analysis-card">
    <h3 class="analysis-title">交易分析</h3>
    <div class="trade-grid">
      <!-- 成交来源 -->
      <!-- {{ sectionData }} -->
      <div class="trade-section">
        <h4 class="section-subtitle">渠道来源</h4>
        <div class="metrics-list">
          <!-- 饼图 -->
          <div class="chart-container">
            <div ref="pieChartRefSource" class="chart"></div>
          </div>
          <!-- 指标列表：动态分组 -->
          <div class="metrics-detail">
            <div v-for="group in getSourceGroupNames()" :key="group" class="channel-group">
              <div class="channel-header">{{ group }}</div>
              <div class="sub-channels">
                <div v-for="(item, index) in getSourceItemsByGroup(group)" :key="index" class="metric-item">
                  <span class="item-label">{{ item.渠道类型 }}</span>
                  <div class="item-values">
                    <span class="amount">{{ item.成交金额 }}</span>
                    <div class="comparison-data">
                      <span :class="getChangeClass(item.较前7日)">
                        {{ item.较前7日 }}
                      </span>
                      <span class="previous-value" v-if="shouldShowPreviousValue(item.较前7日, item.上周期)">
                        上期: {{ formatCurrency(getPreviousValue(item.成交金额, item.较前7日, item.上周期)) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 成交渠道 -->
      <div class="trade-section">
        <h4 class="section-subtitle">成交渠道</h4>
        <div class="metrics-list">
          <!-- 饼图 -->
          <div class="chart-container">
            <div ref="pieChartRefChannel" class="chart"></div>
          </div>

          <!-- 渠道详情 -->
          <div class="metrics-detail">
            <!-- 直播 -->
            <div class="channel-group">
              <div class="channel-header">直播</div>
              <div class="sub-channels">
                <div v-for="(item, index) in getLiveItems()" :key="index" class="metric-item">
                  <span class="item-label">{{ item.渠道类型 }}</span>
                  <div class="item-values">
                    <span class="amount">{{ item.成交金额 }}</span>
                    <div class="comparison-data">
                      <span :class="getChangeClass(item.较前7日)">
                        {{ item.较前7日 }}
                      </span>
                      <span class="previous-value" v-if="shouldShowPreviousValue(item.较前7日, item.上周期)">
                        上期: {{ formatCurrency(getPreviousValue(item.成交金额, item.较前7日, item.上周期)) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 短视频 -->
            <div class="channel-group">
              <div class="channel-header">短视频</div>
              <div class="sub-channels">
                <div v-for="(item, index) in getVideoItems()" :key="index" class="metric-item">
                  <span class="item-label">{{ item.渠道类型 }}</span>
                  <div class="item-values">
                    <span class="amount">{{ item.成交金额 }}</span>
                    <div class="comparison-data">
                      <span :class="getChangeClass(item.较前7日)">
                        {{ item.较前7日 }}
                      </span>
                      <span class="previous-value" v-if="shouldShowPreviousValue(item.较前7日, item.上周期)">
                        上期: {{ formatCurrency(getPreviousValue(item.成交金额, item.较前7日, item.上周期)) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 其他渠道 -->
            <div class="channel-group" style="padding-left: 0;">
              <div class="sub-channels" style="padding-left: 0;">
                <div v-for="(item, index) in getOtherItems()" :key="index" class="metric-item">
                  <span class="item-label" style="font-weight: bold;">{{ item.渠道类型 }}</span>
                  <div class="item-values">
                    <span class="amount">{{ item.成交金额 }}</span>
                    <div class="comparison-data">
                      <span :class="getChangeClass(item.较前7日)">
                        {{ item.较前7日 }}
                      </span>
                      <span class="previous-value" v-if="shouldShowPreviousValue(item.较前7日, item.上周期)">
                        上期: {{ formatCurrency(getPreviousValue(item.成交金额, item.较前7日, item.上周期)) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LabelLayout,
  CanvasRenderer
])

interface TradeItem {
  渠道类型: string;
  渠道分组: string;
  成交金额: string;
  占比: string;
  较前7日: string;
  上周期?: string;
}

interface Props {
  sectionData: any;
}

const props = defineProps<Props>()

const pieChartRefSource = ref<HTMLElement | null>(null)
const pieChartRefChannel = ref<HTMLElement | null>(null)
let pieChartSource: echarts.ECharts | null = null
let pieChartChannel: echarts.ECharts | null = null

// 获取成交渠道数据的所有记录
const getChannelItems = (): TradeItem[] => {
  try {
    if (props.sectionData) {
      // console.log('获取渠道数据', props.sectionData);

      // 如果是字符串，尝试解析
      let data = props.sectionData;
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data);
        } catch (e) {
          console.error('解析渠道数据字符串失败:', e);
        }
      }

      if (Array.isArray(data)) {
        const channelSection = data.find((section: any) => section.title === '成交渠道');
        if (channelSection && channelSection.items && channelSection.items.length > 0) {
          // console.log('找到渠道数据:', channelSection.items[0].value);
          return channelSection.items[0].value || [];
        }
      } else if (data && typeof data === 'object') {
        // 尝试直接访问成交渠道
        if (data['成交渠道'] && data['成交渠道'].items && data['成交渠道'].items.length > 0) {
          // console.log('直接访问渠道数据成功', data['成交渠道'].items[0].value);
          return data['成交渠道'].items[0].value || [];
        }
      }
    }
  } catch (error) {
    console.error('获取渠道数据失败:', error);
  }
  return [];
}

// 获取成交来源数据
const getSourceItems = (): TradeItem[] => {
  try {

    if (props.sectionData) {
      // console.log('获取来源数据', props.sectionData);

      // 如果是字符串，尝试解析
      let data = props.sectionData;
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data);
        } catch (e) {
          console.error('解析来源数据字符串失败:', e);
        }
      }

      if (Array.isArray(data)) {
        const sourceSection = data.find((section: any) => section.title === '渠道来源');
        if (sourceSection && sourceSection.items && sourceSection.items.length > 0) {
          // console.log('找到来源数据:', sourceSection.items[0].value);
          return sourceSection.items[0].value || [];
        }
      } else if (data && typeof data === 'object') {
        // 尝试直接访问渠道来源
        if (data['渠道来源'] && data['渠道来源'].items && data['渠道来源'].items.length > 0) {
          // console.log('直接访问来源数据成功', data['渠道来源'].items[0].value);
          return data['渠道来源'].items[0].value || [];
        }
      }
    }
  } catch (error) {
    // console.error('获取来源数据失败:', error);
  }
  return [];
}

// 获取直播相关的渠道数据
const getLiveItems = (): TradeItem[] => {
  const items = getChannelItems();
  return items.filter(item => item.渠道分组 === '直播');
}

// 获取短视频相关的渠道数据
const getVideoItems = (): TradeItem[] => {
  const items = getChannelItems();
  return items.filter(item => item.渠道分组 === '短视频');
}

// 获取其他渠道数据
const getOtherItems = (): TradeItem[] => {
  const items = getChannelItems();
  return items.filter(item => item.渠道分组 === '其它');
}

// 获取变化率的CSS类
const getChangeClass = (change: string): string => {
  if (!change || change === '--') return '';
  return !change.includes('-') ? 'rate-up' : 'rate-down';
}

// 解析百分比字符串为数值
const parsePercentage = (percentStr: string): number => {
  if (!percentStr || percentStr === '--') return 0;
  return parseFloat(percentStr.replace('%', '')) || 0;
}

// 获取上周期数值的工具函数
const getPreviousValue = (currentValue: string, changeValue: string, previousValue?: string): string => {
  // 优先使用直接提供的上周期值
  if (previousValue && previousValue !== '-' && previousValue !== '--' && previousValue !== '暂无数据') {
    return previousValue
  }

  // 如果当前值或变化值为空，则无法计算
  if (currentValue === '-' || currentValue === '--' || currentValue === '暂无数据' ||
    changeValue === '-' || changeValue === '--' || changeValue === '暂无数据') {
    return '-'
  }

  try {
    // 处理货币符号
    let currentNumeric = parseFloat(currentValue.replace(/[¥,]/g, ''))

    // 去除changeValue的%号和+/-号
    let numericChange = parseFloat(changeValue.replace(/[+,]/g, '').replace('%', ''))
    
    // 当变化率为 -100%（表示从0增长到当前值）或接近-100%时，直接返回0或标记
    if (numericChange <= -99.9) {
      return '0'
    }
    
    // 根据变化是正值还是负值来计算
    if (changeValue.includes('-')) {
      // 防止除以零的情况
      if (Math.abs(1 + numericChange / 100) < 0.0001) {
        return '0'
      }
      // 上期值 = 当前值 / (1 - 变化百分比的绝对值/100)
      return formatNumber(currentNumeric / (1 + numericChange / 100))
    } else {
      // 防止除以零的情况
      if (Math.abs(1 + numericChange / 100) < 0.0001) {
        return '0'
      }
      // 上期值 = 当前值 / (1 + 变化百分比)
      return formatNumber(currentNumeric / (1 + (numericChange / 100)))
    }
  } catch (e) {
    // 计算出错，尝试返回原始值
    return currentValue
  }
}

// 格式化数字，不保留小数位
const formatNumber = (num: number): string => {
  if (num === 0) return '0'

  // 四舍五入到整数并添加千位分隔符
  return Math.round(num).toLocaleString('zh-CN')
}

// 初始化饼图配置
const initPieChart = (data: Array<{ name: string, value: number, percentage: string }>) => {
  return {
    series: [{
      type: 'pie',
      radius: '55%',
      center: ['50%', '40%'],
      data: data,
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        position: 'outside',
        formatter: (params: any) => {
          // 显示名称和占比
          return `${params.name}\n${params.data.percentage}`;
        },
        fontSize: 12,
        fontWeight: 'normal',
        color: '#666'
      },
      labelLine: {
        show: true,
        length: 15,
        length2: 10,
        smooth: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }],
    legend: {
      show: true,
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 25,
      textStyle: {
        fontSize: 12,
        color: '#666'
      },
      padding: [20, 0]
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        // 在提示框中显示名称、金额和占比
        return `${params.name}<br/>金额: ${params.data.amount}<br/>占比: ${params.data.percentage}`;
      }
    }
  }
}

// 获取渠道来源所有分组名（去重）
const getSourceGroupNames = (): string[] => {
  const items = getSourceItems();
  const groupSet = new Set<string>();
  items.forEach(item => {
    if (item.渠道分组) groupSet.add(item.渠道分组);
  });
  return Array.from(groupSet);
};

// 获取某分组下的渠道来源明细
const getSourceItemsByGroup = (group: string): TradeItem[] => {
  const items = getSourceItems();
  return items.filter(item => item.渠道分组 === group);
};

// 更新来源饼图（动态分组合计）
const updateSourceChart = () => {
  console.log('更新来源饼图');
  if (!pieChartRefSource.value) {
    console.warn('来源饼图DOM未就绪');
    return;
  }

  if (!pieChartSource) {
    console.log('初始化来源饼图');
    pieChartSource = echarts.init(pieChartRefSource.value);
  }

  const items = getSourceItems();
  // 动态分组合计
  const groupMap: Record<string, {amount: number, percent: number}> = {};
  items.forEach(item => {
    const group = item.渠道分组 || '未分组';
    if (!groupMap[group]) groupMap[group] = {amount: 0, percent: 0};
    const numAmount = parseFloat((item.成交金额 || '').replace(/[^\d.\-]/g, ''));
    const numPercent = parseFloat((item.占比 || '').replace('%', ''));
    groupMap[group].amount += isNaN(numAmount) ? 0 : numAmount;
    groupMap[group].percent += isNaN(numPercent) ? 0 : numPercent;
  });
  const sourceData = Object.entries(groupMap).map(([group, val]) => ({
    name: group,
    value: val.percent,
    percentage: val.percent.toFixed(2) + '%',
    amount: '¥' + val.amount.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2})
  }));
  console.log('来源饼图数据:', sourceData);
  if (sourceData.length > 0) {
    pieChartSource.setOption(initPieChart(sourceData), true);
  } else {
    console.warn('来源饼图数据为空');
  }
}

// 更新渠道饼图
const updateChannelChart = () => {
  console.log('更新渠道饼图');
  if (!pieChartRefChannel.value) {
    console.warn('渠道饼图DOM未就绪');
    return;
  }

  if (!pieChartChannel) {
    console.log('初始化渠道饼图');
    pieChartChannel = echarts.init(pieChartRefChannel.value);
  }

  const items = getChannelItems();

  // 合并直播和短视频
  const groupSum = (group: string) => {
    const groupItems = items.filter(item => item.渠道分组 === group);
    // 金额合计
    const totalAmount = groupItems.reduce((sum, item) => {
      const num = parseFloat((item.成交金额 || '').replace(/[^\d.\-]/g, ''));
      return sum + (isNaN(num) ? 0 : num);
    }, 0);
    // 占比合计
    const totalPercent = groupItems.reduce((sum, item) => {
      const num = parseFloat((item.占比 || '').replace('%', ''));
      return sum + (isNaN(num) ? 0 : num);
    }, 0);
    return {
      amount: totalAmount,
      percent: totalPercent
    };
  };

  const live = groupSum('直播');
  const video = groupSum('短视频');

  // 其它分组下每个渠道类型单独显示
  const otherItems = items.filter(item => item.渠道分组 === '其它').map(item => ({
    name: item.渠道类型,
    value: parseFloat((item.占比 || '').replace('%', '')),
    percentage: (parseFloat((item.占比 || '').replace('%', '')) || 0).toFixed(2) + '%',
    amount: item.成交金额
  }));

  const channelData = [
    {
      name: '直播',
      value: live.percent,
      percentage: live.percent.toFixed(2) + '%',
      amount: '¥' + live.amount.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2})
    },
    {
      name: '短视频',
      value: video.percent,
      percentage: video.percent.toFixed(2) + '%',
      amount: '¥' + video.amount.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2})
    },
    ...otherItems
  ];

  console.log('渠道饼图数据:', channelData);

  if (channelData.length > 0) {
    console.log('设置渠道饼图选项');
    pieChartChannel.setOption(initPieChart(channelData), true);
  } else {
    console.warn('渠道饼图数据为空');
  }
}

// 监听数据变化，更新图表
watch(() => props.sectionData, () => {
  console.log('sectionData变化:', props.sectionData);
  // 使用setTimeout确保DOM已更新
  setTimeout(() => {
    updateSourceChart();
    updateChannelChart();
  }, 0);
}, { deep: true, immediate: true });

// 监听sectionData.value变化
watch(() => props.sectionData?.value, () => {
  console.log('sectionData.value变化:', props.sectionData?.value);
  // 使用setTimeout确保DOM已更新
  setTimeout(() => {
    updateSourceChart();
    updateChannelChart();
  }, 0);
}, { deep: true, immediate: true });

// 初始化图表
onMounted(() => {
  console.log('组件挂载完成');
  setTimeout(() => {
    updateSourceChart();
    updateChannelChart();
  }, 100);

  // 响应窗口大小变化
  const handleResize = () => {
    pieChartSource?.resize();
    pieChartChannel?.resize();
  }

  window.addEventListener('resize', handleResize);
})

// 组件销毁时清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    pieChartSource?.resize();
    pieChartChannel?.resize();
  });

  // 销毁图表实例
  pieChartSource?.dispose();
  pieChartChannel?.dispose();
})

const shouldShowPreviousValue = (change: string, prev: string | undefined) => {
  const isEmpty = (val: any) =>
    val === undefined || val === null || val === '' || val === '-' || val === '--';
  return !(isEmpty(change) && isEmpty(prev));
};

const formatCurrency = (val: string | number) => {
  let num = typeof val === 'number' ? val : parseFloat((val || '').toString().replace(/[^\d.\-]/g, ''));
  if (isNaN(num)) return '-';
  return '¥' + num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};
</script>

<style scoped>
.analysis-card {
  margin-bottom: 25px;
  padding: 25px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.analysis-title {
  font-size: 20px;
  color: #2d3748;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e2e8f0;
}

.trade-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  max-width: 100%;
  overflow: hidden;
  color: #000;
}

.trade-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  min-width: 0;
  overflow: hidden;
}

.section-subtitle {
  font-size: 16px;
  color: #4a5568;
  margin-bottom: 16px;
  padding-left: 10px;
  border-left: 3px solid #4a5568;
}

.metrics-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.channel-group {
  background: #ffffff;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 12px;
}

.channel-header {
  font-size: 15px;
  font-weight: bold;
  background: #f3f4f6;
  color: #222;
  border-radius: 4px;
  padding: 6px 12px;
  margin-bottom: 8px;
  display: inline-block;
}

.sub-channels {
  padding-left: 12px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #ffffff;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.metric-item:hover {
  background: #f0f4f8;
}

.item-label {
  font-size: 14px;
  color: #4a5568;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-values {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.amount {
  font-size: 16px;
  font-weight: bold;
  color: #2d3748;
  text-align: right;
  min-width: 80px;
  display: block;
}

.percentage {
  font-size: 14px;
  color: #718096;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rate-up,
.rate-down {
  font-size: 13px;
  padding: 2px 6px;
  border-radius: 4px;
}

.rate-up {
  color: #22c55e;
  background: rgba(34, 197, 94, 0.1);
}

.rate-down {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.1);
}

.comparison-data {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.previous-value {
  font-size: 11px;
  color: #718096;
  text-align: right;
  display: block;
}

@media (max-width: 768px) {
  .trade-grid {
    grid-template-columns: 1fr;
  }

  .item-values {
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;
  }
}

/* 添加图表相关样式 */
.chart-container {
  height: 300px;
  margin-bottom: 20px;
  width: 100%;
  overflow: hidden;
}

.chart {
  width: 100%;
  height: 100%;
  min-width: 0;
}

.metrics-detail {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px;
  overflow: hidden;
  width: 100%;
  box-sizing: border-box;
}
</style>